from tkinter import Tk, messagebox

import tkinter as tk

from operate_GUI import display_operate


def read_data():
    with open("./data.txt", 'r') as f:
        rows = f.readlines()
        user_info_list = {}
        for row in rows:
            dict_list = row.strip().split(":")
            user_info_list[dict_list[0]] = dict_list[1]
        f.close()
    return user_info_list


# 登陆界面
def display_login():
    root = Tk()

    root.title("登陆")

    screen_width, screen_height = root.maxsize()

    width = 400
    height = 200
    align_str = "%dx%d+%d+%d" % (width, height, (screen_width - width) / 2, (screen_height - height) / 2)

    root.geometry(align_str)
    root.resizable(width=False, height=True)

    def user_login():
        name = user_name_text.get()
        pwd = user_pwd_text.get()
        user_dict = read_data()
        if name != '' and pwd != "":
            if name in user_dict.keys():
                if pwd == user_dict[name]:
                    messagebox.showinfo(title="Okay!", message="Welcome to Connect!")
                    root.destroy()
                    display_operate()
                else:
                    messagebox.showerror(title="ERROR", message="Incorrect Password!")
            else:
                messagebox.showerror(title="ERROR", message="Incorrect User Name!")
        else:
            messagebox.showerror(title="ERROR", message="User Name and Password Can't Be Empty!")

    user_name_label = tk.Label(root, text="账号", font=("HeiTi", 14))
    user_name_label.place(x=80, y=30)

    user_pwd_label = tk.Label(root, text="密码", font=("HeiTi", 14))
    user_pwd_label.place(x=80, y=80)

    user_name_text = tk.StringVar()
    user_name_text.set("输入账号")
    user_name_entry = tk.Entry(root, textvariable=user_name_text, font=("FangSong", 16))
    user_name_entry.place(x=160, y=30)

    user_pwd_text = tk.StringVar()
    user_pwd_text.set("输入密码")
    user_pwd_entry = tk.Entry(root, textvariable=user_pwd_text, font=("FangSong", 16))
    user_pwd_entry.place(x=160, y=80)

    user_login_btn = tk.Button(root, text="登陆", font=("FangSong", 16), command=user_login)
    user_login_btn.place(x=120, y=140)

    back_btn = tk.Button(root, text="退出", font=("FangSong", 16), command=root.destroy)
    back_btn.place(x=180, y=140)

    root.mainloop()


display_login()
